var workshopSelect = [];
$(function () {
    info();
    var workshopId = document.getElementById("workshopId").value;
    document.getElementById("startTime").value = DateUtil.changeDateToString(new Date().getTime(), DateFormatEnum.YYYY_MM_DD);
    document.getElementById("endTime").value = DateUtil.changeDateToString(new Date().getTime(), DateFormatEnum.YYYY_MM_DD);
    DayList(workshopId, new Date().getTime(), new Date().getTime());
    //导出
    $("#daochu").click(function () {
        var load = LayerUtil.loading();
        var startTime = document.getElementById("startTime").value;
        var endTime = document.getElementById("endTime").value;
        var workshopId = document.getElementById("workshopId").value;
        Request.builder()
            .url(HOME_LIST)
            .isToken(true)
            .data({
                "workshopId": workshopId,
                "startTime": new Date(startTime.replace(/-/g, "/")).getTime(),
                "endTime": new Date(endTime.replace(/-/g, "/")).getTime(),
                "export": 1
            })
            .callback(function (e) {
                if (e.code === "00000") {
                    LayerUtil.successMsg("文件生成成功，开始下载...");
                    layer.close(load);
                    window.location.href = e.data;
                } else {
                    LayerUtil.failMsg(e.msg ? e.msg : "生成失败");
                }
            }).get();
    });
});

function info() {
    var index = LayerUtil.loading();
    if (Store.get('sftCompanyToken')) {
        Request.builder()
            .url(HOME_INFO)
            .isToken(true)
            .callback(function (e) {
                if (e.code === "00000") {
                    var data = e.data;
                    Form.setHtml($("#infoDiv"), data);
                    layer.close(index);
                    workshopSelect = e.workshopList.resultData;
                    if (workshopSelect.length > 0) {
                        Select.builder().data(workshopSelect).initByData();
                    }
                } else {
                    LayerUtil.failMsg(e.msg != null ? e.msg : ERROR_MSG.FAIL);
                }
            }).get();
    } else {
        LayerUtil.failMsg('请先登录后操作')
        setTimeout(() => {
            window.location.href = LOGIN_VIEW
        }, 1000)
    }

}

function touwei(data) {
    var trend_default_option = {
        tooltip: {
            trigger: 'axis',
            formatter: function (params) {
                var html = '';
                for (var i = 1; i < params.length; i++) {
                    html += '<div style="color: #000;font-size: 14px; padding:0 6px;line-height: 24px">';
                    html += '<span style="display:inline-block;margin:0 10px;border-radius:2px;width:10px;height:10px;background-color:' + params[i].color + ';"></span>';
                    html += params[i].seriesName + ' <span class="number m-l-md pull-right" style="margin-left:10px">' + params[i].data + 'g</span>';
                    html += '</div>';
                }
                return html;
            }
        },
        grid: {left: '53', top: '30', right: '7', bottom: '45'},
        xAxis: {
            type: 'category',
            data: [],
            axisTick: {alignWithLabel: true},
            axisLine: {show: true},
            name: '',
            axisLabel: {
                margin: 20
            }
        },
        yAxis: [
            {type: 'value', name: '', min: 0, nameTextStyle: {align: "right"}, axisLabel: {formatter: '{value} '}},
            {type: 'value', name: '', min: 0, axisLabel: {formatter: '{value} '}},
        ],
        dataZoom: [
            { //y轴固定,让内容滚动
                type: 'slider',
                xAxisIndex: [0],
                show: true, //显示滚轴
                height: 6, //设置滚轴的高度
                bottom: 0, //设置滚轴在底部
                start: 0,
                end: 80,//设置X轴刻度之间的间隔(根据数据量来调整)
                zoomLock: true, //锁定区域禁止缩放(鼠标滚动会缩放,所以禁止)
                minValueSpan: 15,//用于限制窗口大小的最小值（实际数值）。
                maxValueSpan: 15,//用于限制窗口大小的最大值（实际数值）。
                realtime: true,//拖动时，是否实时更新系列的视图。如果设置为 false，则只在拖拽结束的时候更新
                showDetail: false,//即拖拽时候滚动条两侧不显示信息 默认true
                filterMode: 'empty' // 溢出窗口数据隐藏
            },
        ],
        series: [
            {
                type: 'bar',
                itemStyle: {
                    color: function (params) {
                        return 'rgba(0,0,0,0.05)';
                    }
                },
                emphasis: {
                    itemStyle: {
                        color: 'rgba(0,0,0,0.15)'
                    }
                },
                barGap: '-100%',
                barCategoryGap: '20%',
                barWidth: 35,
                data: [],
                animation: false
            },
            {
                name: '执行投喂',
                lineStyle: {width: 2},
                itemStyle: {normal: {color: '#73BFA9'}},
                type: 'bar',
                stack: 'f',
                smooth: true,
                barWidth: 35,
                data: []
            },
            {
                name: '补充投喂',
                lineStyle: {width: 2},
                itemStyle: {normal: {color: '#4996CF'}},
                type: 'bar',
                stack: 'f',
                smooth: true,
                barWidth: 35,
                data: []
            },
            {
                name: '实际投喂',
                symbolSize: 2,
                rippleEffect: { // 可选，设置涟漪效果
                    period: 0, // 动画持续时间
                },
                itemStyle: {normal: {color: '#af64bb'}},
                type: 'effectScatter',
                smooth: false,
                data: []
            },
        ]
    };
    var xaxis = [];
    var shadow = [];
    var sdata0 = [];
    var sdata1 = [];
    var sdata2 = [];
    var max = 0;
    data.forEach(function (item) {
        xaxis.push(item.name);
        shadow.push(0);
        sdata0.push(item.feedWeight - item.replenishWeight);
        sdata1.push(item.replenishWeight);
        sdata2.push(item.feedWeight);
        max = item.feedWeight > max ? item.feedWeight : max;
    });
    max = max ? parseInt(Math.ceil(max / 100)) * 150 : 100
    shadow.fill(max);
    var trend_option = $.extend({}, trend_default_option);
    trend_option.xAxis.data = xaxis;
    trend_option.series[0].data = shadow;
    trend_option.series[1].data = sdata0;
    trend_option.series[2].data = sdata1;
    trend_option.series[3].data = sdata2;
    trend_option.yAxis[0].max = max;
    trend_option.yAxis[1].max = max;
    trend_option.yAxis[0].interval = parseInt(Math.ceil(max / 100)) * 20 > 0 ? parseInt(Math.ceil(max / 100)) * 20 : 20;
    trend_option.yAxis[1].interval = parseInt(Math.ceil(max / 100)) * 20 > 0 ? parseInt(Math.ceil(max / 100)) * 20 : 20;
    var chart = echarts.init(document.getElementById('feed_chart'));
    chart.setOption(trend_option);
    setInterval(() => {
        chart.resize();
    }, 100)
}

function DayList(workshopId, startTime, endTime) {
    Request.builder()
        .url(HOME_LIST)
        .isToken(true)
        .data({"workshopId": workshopId, "startTime": startTime, "endTime": endTime})
        .callback(function (e) {
            if (e.code === "-50") {
                LayerUtil.failMsg(e.msg)
                return false;
            }
            touwei(e.data.homeChartLists)
            var html = "";
            var data = e.data.homeStationLists;
            if (data.length > 0) {
                $.each(data, function (index, item) {
                    html += '<tr>\n' +
                        '<th scope="row"  style="text-align: center;">' + (index + 1) + '</th>\n' +
                        '<td>' + item.name + '</td>\n' +
                        '<td class="thtd_style1">' + item.speciesSpec + '</td>\n' +
                        '<td class="thtd_style1">' + item.speciesNum + '</td>\n' +
                        '<td class="thtd_style2">' + item.executeWeight + '</td>\n' +
                        '<td class="thtd_style1">' + item.executeNum + '</td>\n' +
                        '<td class="thtd_style3">' + item.replenishWeight + '</td>\n' +
                        '<td class="thtd_style1">' + item.replenishNum + '</td>\n' +
                        '<td class="thtd_style4">' + item.feedWeight + '</td>\n' +
                        '<td class="thtd_style1">' + item.feedNum + '</td>\n';
                    if (item.tempType === 0) {
                        var waterTemp = item.waterTemp;
                        if (waterTemp < 1 || waterTemp > 35) {
                            waterTemp = -100;
                        }
                        if (waterTemp === -100) {
                            html += '<td class="thtd_style5">' + '##' + '</td>\n';
                        } else {
                            html += '<td class="thtd_style5">' + parseFloat(waterTemp).toFixed(1) + '</td>\n';
                        }
                    } else {
                        var airTemp = item.airTemp;
                        if (airTemp < 1 || airTemp > 35) {
                            airTemp = -100;
                        }
                        if (airTemp === -100) {
                            html += '<td class="thtd_style5">' + '##' + '</td>\n';
                        } else {
                            html += '<td class="thtd_style5">' + parseFloat(airTemp).toFixed(1) + '</td>\n';
                        }
                    }
                    html += '<td>' + item.baitBrandName + '</td>\n' +
                        '<td class="thtd_style1">' + item.baitSizeName + '</td>\n' +
                        '</tr>\n';
                })
            } else {
                html += '<tr class="text-center font-weight-bold fs-18 no-records-found"><td colspan="14">该日期下暂无数据</td></tr>'
            }
            $("#workShopUsedList").html(html);
        }).get();
}

function searchDayBtn() {
    var startTime = document.getElementById("startTime").value;
    var endTime = document.getElementById("endTime").value;
    var workshopId = document.getElementById("workshopId").value;
    DayList(workshopId, new Date(startTime.replace(/-/g, "/")).getTime(), new Date(endTime.replace(/-/g, "/")).getTime());
}